using System;
using System.Text.RegularExpressions;
using UnityEngine.SceneManagement;

namespace UnityEngine.Recorder
{
	[Serializable]
	public struct FileNameGenerator
	{
		public enum ETags
		{
			Time,
			Date,
			Project,
			Product,
			Scene,
			Resolution,
			Frame,
			Extension
		}

		private static string m_projectName;

		[SerializeField]
		private string m_Pattern;

		private string m_FramePattern;

		private string m_FramePatternDst;

		public static string[] tagLabels
		{
			get;
			private set;
		}

		public static string[] tags
		{
			get;
			private set;
		}

		public string pattern
		{
			get
			{
				return m_Pattern;
			}
			set
			{
				m_Pattern = value;
			}
		}

		static FileNameGenerator()
		{
			tags = new string[8]
			{
				"<ts>",
				"<dt>",
				"<prj>",
				"<prd>",
				"<scn>",
				"<res>",
				"<00000>",
				"<ext>"
			};
			tagLabels = new string[8]
			{
				"<ts>  - Time",
				"<dt>  - Date",
				"<prj> - Project name",
				"<prd> - Product name (editor only)",
				"<scn> - Scene name",
				"<res> - Resolution",
				"<000> - Frame number",
				"<ext> - Default extension"
			};
		}

		public static string AddTag(string pattern, ETags t)
		{
			if (!string.IsNullOrEmpty(pattern))
			{
				pattern = ((t != ETags.Frame && t != ETags.Extension) ? (pattern + "-") : (pattern + "."));
			}
			pattern += tags[(int)t];
			return pattern;
		}

		public string BuildFileName(RecordingSession session, int frame, int width, int height, string ext)
		{
			if (string.IsNullOrEmpty(m_projectName))
			{
				m_projectName = "N/A";
			}
			Regex regex = new Regex("(<0*>)");
			Match match = regex.Match(pattern);
			if (match.Success)
			{
				m_FramePattern = match.Value;
				m_FramePatternDst = m_FramePattern.Substring(1, m_FramePattern.Length - 2);
			}
			else
			{
				m_FramePattern = "<0>";
				m_FramePatternDst = "0";
			}
			return pattern.Replace(tags[7], ext).Replace(tags[5], $"{width}x{height}").Replace(m_FramePattern, frame.ToString(m_FramePatternDst))
				.Replace(tags[4], SceneManager.GetActiveScene().name)
				.Replace(tags[2], m_projectName)
				.Replace(tags[3], "(prd-NA)")
				.Replace(tags[0], string.Format("{0}h{1}m", session.m_SessionStartTS.ToString("HH"), session.m_SessionStartTS.ToString("mm")))
				.Replace(tags[1], session.m_SessionStartTS.ToShortDateString().Replace('/', '-'));
		}
	}
}
